﻿using System;
using UnityEngine;

namespace RTR.ShadingBasic
{
    public class Game : MonoBehaviour
    {
        public Color color = Color.black;
        public Renderer cube;
        public Material material;
        public Camera camera;
        public Light directionalLight;
        public Light pointLight;
        public Light spotLight;

        private Mesh mesh;

        private void Awake()
        {
            mesh = cube.GetComponent<MeshFilter>().mesh;
            mesh.colors = new Color[mesh.vertexCount];
        }

        private void LateUpdate()
        {
            // 更新材质矩阵等等
            if (mesh == null || material == null) return;

            material.SetColor("color", color);

            material.SetMatrix("objectToWorldMatrix", cube.localToWorldMatrix);
            material.SetMatrix("worldToObjectMatrix", cube.worldToLocalMatrix);
            material.SetMatrix("mvpMatrix", GL.GetGPUProjectionMatrix(camera.projectionMatrix, true) * camera.worldToCameraMatrix * cube.localToWorldMatrix);
            
            material.SetVector("cameraPosition", camera.transform.position);
            
            material.SetVector("directionalLightDirection", directionalLight.transform.forward);
            material.SetVector("directionalLightColor", directionalLight.color.linear);
            
            material.SetVector("pointLightPosition", pointLight.transform.position);
            material.SetVector("pointLightColor", pointLight.color.linear);
            material.SetFloat("pointLightMinDistance", 1.01f);
            material.SetFloat("pointLightMaxDistance", pointLight.range);
            
            material.SetVector("spotLightPosition", spotLight.transform.position);
            material.SetVector("spotLightColor", spotLight.color.linear);
            material.SetVector("spotLightDir", spotLight.transform.forward); ;
            material.SetFloat("spotLightMinDistance", 1.01f);
            material.SetFloat("spotLightMaxDistance", spotLight.range);
            material.SetFloat("spotLightCosP", Mathf.Cos(spotLight.innerSpotAngle * Mathf.Deg2Rad));
            material.SetFloat("spotLightCosU", Mathf.Cos(spotLight.spotAngle * Mathf.Deg2Rad));
        }
    }
}